package com.wmjsoft.plugins.nutzplugin

import com.alibaba.druid.pool.DruidDataSource
import com.alibaba.fastjson.JSONObject
import com.wmjsoft.plugins.nutzplugin.dao.MyDao
import com.wmjsoft.plugins.nutzplugin.dao.Pool
import net.cloudopt.next.web.Plugin
import net.cloudopt.next.web.config.ConfigManager
import org.nutz.dao.impl.NutDao
import org.nutz.dao.util.Daos


/**
 * 如果我没有写注释，请提醒我
 * @program: Maternal
 * @description:
 * @author: Mr.Lee
 * @create: 2021-02-19 17:46
 */
class NutzPlugin:Plugin {
    override fun start(): Boolean {
        val config = ConfigManager.init("dao")
        println("DaoPlugin is $config")
        Pool.dataSource = DruidDataSource()
        val pool = config["pool"] as JSONObject

        Pool.dataSource.url = config["jdbcUrl"] as String
        Pool.dataSource.username = config["username"] as String
        Pool.dataSource.password = config["password"] as String
        Pool.dataSource.driverClassName = config["driverClassName"] as String
        Pool.dataSource.maxActive = pool["maxActive"] as Int ?: 8
        Pool.dataSource.initialSize = pool["initialSize"] as Int ?: 0
        Pool.dataSource.minIdle = pool["minIdle"] as Int ?: 5
        Pool.dataSource.removeAbandonedTimeout = pool["removeAbandonedTimeout"] as Int ?: 60

        MyDao.dao = NutDao(Pool.dataSource)

        if(config["ddl"] as Boolean) {
            val packagePath = config["modelPackage"] as String
            Daos.createTablesInPackage(MyDao.dao,packagePath,false)
            Daos.migration(MyDao.dao,packagePath,true,true)
        }



        return true
    }

    override fun stop(): Boolean {
        Pool.dataSource.close()
        return true
    }
}

